// services/ttsHistory.js - Updated with caption and download support

import { ipcMain, shell, dialog, app } from 'electron'
import path from 'path'
import fs from 'fs'
import {
  getAllTtsHistory,
  addTtsHistory,
  getTtsHistoryById,
  deleteTtsHistory,
  searchTtsHistory,
  deleteAllTtsHistory,
  initTtsHistoryTable,
  sendToKpop,
  updateTtsHistoryCaption,
  downloadAudioFile,
  downloadCaptionFile,
  batchDownloadFiles,
  getCaptionContent,
  updateTtsHistoryId,
  getCaptionContentWithPath
} from '../dao/ttsHistory.js'


export function init() {
  // 初始化表结构（确保有所有字段）
  initTtsHistoryTable();

  // 获取所有TTS历史记录
  ipcMain.handle('ttsHistory/getAll', () => {
    return getAllTtsHistory()
  })

  // 添加新TTS历史记录（更新为接收对象参数）
  ipcMain.handle('ttsHistory/add', (event, data) => {
    return addTtsHistory(data)
  })

  // 添加新TTS历史记录（更新为接收对象参数）
  ipcMain.handle('ttsHistory/update', (event, id, historyId) => {
    return updateTtsHistoryId(id, historyId)
  })

  // 更新字幕信息
  ipcMain.handle('ttsHistory/updateCaption', (event, id, captionPath, captionStatus, captionError) => {
    return updateTtsHistoryCaption(id, captionPath, captionStatus, captionError)
  })

  // 根据ID获取TTS历史记录
  ipcMain.handle('ttsHistory/getById', (event, id) => {
    return getTtsHistoryById(id)
  })

  // 删除TTS历史记录
  ipcMain.handle('ttsHistory/delete', (event, id) => {
    return deleteTtsHistory(id)
  })

  // 删除所有TTS历史记录
  ipcMain.handle('ttsHistory/deleteAll', () => {
    return deleteAllTtsHistory()
  })

  // 搜索TTS历史记录
  ipcMain.handle('ttsHistory/search', (event, keyword) => {
    return searchTtsHistory(keyword)
  })

  // 获取字幕内容
  ipcMain.handle('ttsHistory/getCaptionContent', (event, id) => {
    try {
      return getCaptionContent(id)
    } catch (error) {
      throw new Error(error.message)
    }
  })

  // 获取字幕内容
  ipcMain.handle('ttsHistory/getCaptionContentWithPath', (event, CaptionPath) => {
    try {
      return getCaptionContentWithPath(CaptionPath)
    } catch (error) {
      throw new Error(error.message)
    }
  })

  // 下载单个音频文件
  ipcMain.handle('ttsHistory/downloadAudio', async (event, id) => {
    try {
      const fileInfo = downloadAudioFile(id)

      // 打开保存对话框
      const result = await dialog.showSaveDialog({
        defaultPath: path.join(app.getPath('downloads'), `${fileInfo.name}_audio${path.extname(fileInfo.fileName)}`),
        filters: [
          { name: 'Audio Files', extensions: ['mp3', 'wav', 'ogg', 'm4a'] },
          { name: 'All Files', extensions: ['*'] }
        ]
      })

      if (!result.canceled && result.filePath) {
        // 复制文件到用户选择的位置
        fs.copyFileSync(fileInfo.filePath, result.filePath)
        // 在文件管理器中显示文件
        shell.showItemInFolder(result.filePath)
        return { success: true, filePath: result.filePath }
      }

      return { success: false, canceled: true }
    } catch (error) {
      throw new Error(error.message)
    }
  })

  // 下载单个字幕文件
  ipcMain.handle('ttsHistory/downloadCaption', async (event, id) => {
    try {
      const fileInfo = downloadCaptionFile(id)

      // 打开保存对话框
      const result = await dialog.showSaveDialog({
        defaultPath: path.join(app.getPath('downloads'), `${fileInfo.name}_caption${path.extname(fileInfo.fileName)}`),
        filters: [
          { name: 'Subtitle Files', extensions: ['srt', 'vtt', 'txt'] },
          { name: 'All Files', extensions: ['*'] }
        ]
      })

      if (!result.canceled && result.filePath) {
        // 复制文件到用户选择的位置
        fs.copyFileSync(fileInfo.filePath, result.filePath)
        // 在文件管理器中显示文件
        shell.showItemInFolder(result.filePath)
        return { success: true, filePath: result.filePath }
      }

      return { success: false, canceled: true }
    } catch (error) {
      throw new Error(error.message)
    }
  })

  // 批量下载文件
  ipcMain.handle('ttsHistory/batchDownload', async (event, ids, includeAudio = true, includeCaption = true) => {
    try {
      const zipInfo = await batchDownloadFiles(ids, includeAudio, includeCaption)

      // 打开保存对话框
      const result = await dialog.showSaveDialog({
        defaultPath: path.join(app.getPath('downloads'), zipInfo.fileName),
        filters: [
          { name: 'ZIP Files', extensions: ['zip'] },
          { name: 'All Files', extensions: ['*'] }
        ]
      })

      if (!result.canceled && result.filePath) {
        // 移动文件到用户选择的位置
        fs.renameSync(zipInfo.filePath, result.filePath)
        // 在文件管理器中显示文件
        shell.showItemInFolder(result.filePath)

        // 清理临时目录
        const tempDir = path.dirname(zipInfo.filePath)
        fs.rmSync(tempDir, { recursive: true, force: true })

        return { success: true, filePath: result.filePath }
      } else {
        // 用户取消，清理临时文件
        fs.unlinkSync(zipInfo.filePath)
        const tempDir = path.dirname(zipInfo.filePath)
        fs.rmSync(tempDir, { recursive: true, force: true })
      }

      return { success: false, canceled: true }
    } catch (error) {
      console.log(JSON.stringify(error))
      throw new Error(error.message)
    }
  })

  // 混剪
  ipcMain.handle('ttsHistory/sendVideoToKpop', (event, audioItems, uuidv) => {
    return sendToKpop(audioItems, uuidv)
  })
}
